package cn.congine.wizarpos.mall.tenpay;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import org.apache.commons.codec.binary.Hex;

import cn.congine.wizarpos.mall.utils.WxSignUtil;

import com.fasterxml.jackson.annotation.JsonProperty;

public class WechatPayment {
	@JsonProperty("appId")
	private String appId;

	@JsonProperty("timeStamp")
	private String timestamp;

	@JsonProperty("nonceStr")
	private String noncestr;

	@JsonProperty("paymentPackage")
	private String paymentPackage;

	@JsonProperty("signType")
	private String signType = "MD5";

	@JsonProperty("paySign")
	private String sign;

	public String getAppId() {
		return appId;
	}

	public void setAppId(String appId) {
		this.appId = appId;
	}

	public String getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}

	public String getNoncestr() {
		return noncestr;
	}

	public void setNoncestr(String noncestr) {
		this.noncestr = noncestr;
	}

	public String getPaymentPackage() {
		return paymentPackage;
	}

	public void setPaymentPackage(String paymentPackage) {
		this.paymentPackage = paymentPackage;
	}

	public String getSignType() {
		return signType;
	}

	public void setSignType(String signType) {
		this.signType = signType;
	}

	public String getSign() {
		return sign;
	}

	public void setSign(String sign) {
		this.sign = sign;
	}

	public void sign(String appId, String paternerKey) {
		setAppId(appId);
		setTimestamp(String.valueOf(WxSignUtil.createTimestamp()));
		setNoncestr(WxSignUtil.getMD5Radom());

		Map<String, String> map = new HashMap<String, String>();
		map.put("appId", getAppId());
		map.put("timeStamp", getTimestamp());
		map.put("nonceStr", getNoncestr());
		map.put("signType", getSignType());
		map.put("package", getPaymentPackage());

		StringBuffer sb = new StringBuffer();
		SortedSet<String> keys = new TreeSet<String>(map.keySet());
		Iterator<String> it = keys.iterator();
		while (it.hasNext()) {
			String key = it.next();
			String value = map.get(key);
			sb.append(key).append("=").append(value);
			if (it.hasNext()) {
				sb.append("&");
			}
		}
		sb.append("&key=" + paternerKey);

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(sb.toString().getBytes("UTF-8"));
			byte[] array = md.digest();
			String sign = new String(Hex.encodeHex(array));
			setSign(sign.toUpperCase());
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
		}
	}

}
